package questionSolution.Question_49;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/*
异位词的本质是“字符种类和数量完全相同”，因此可以通过统计每个字符串中字符的出现次数，生成一个唯一的“计数标识”作为哈希表的键
 */
public class Solution_2 {
    public List<List<String>> groupAnagrams(String[] strs){
        List<List<String>> res = new ArrayList<>();
        HashMap<String, List<String>> map = new HashMap<>();
        for (String str : strs){
            char[] chars = str.toCharArray();
            int[] count = new int[26];
            for(char c : chars){
                count[c - 'a']++;
            }
            StringBuilder key = new StringBuilder();
            for(int num : count){
                key.append(num).append(',');
            }
            String keystr = key.toString();
            map.computeIfAbsent(keystr, k -> new ArrayList<>()).add(str);
        }
        for(List<String> s : map.values()){
            res.add(s);
        }
        return res;
    }

    static void main() {
        Solution_2 sol = new Solution_2();
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        System.out.println(sol.groupAnagrams(strs));
    }
}
